﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Slb.Ocean.Core;

using Public.Ocean.Petrel.Extensions.Internal;
using System.ComponentModel;

namespace Public.Ocean.Petrel.Extensions.Attributes
{
    public class CustomAttributeEventService
    {
        public static readonly CustomAttributeEventService Instance = new CustomAttributeEventService();
        Dictionary<Droid, Dictionary<string, List<PropertyChangedEventHandler>>> table;

        private CustomAttributeEventService()
        {
            table = new Dictionary<Droid, Dictionary<string, List<PropertyChangedEventHandler>>>();
            DataManager.WorkspaceClosed += delegate
            {
                DetachAll();
            };
        }

        public void Attach(CustomAttributesBase attribute, string key, PropertyChangedEventHandler handler)
        {
            var bag = table.GetOrAddNew(attribute.GetDroid());
            var handlers = bag.GetOrAddNew(key);
            handlers.Add(handler);
        }

        public void Detach(CustomAttributesBase attribute, string key, PropertyChangedEventHandler handler)
        {
            var bag = table.GetOrReturnNew(attribute.GetDroid());
            var handlers = bag.GetOrReturnNew(key);
            handlers.Remove(handler);
        }

        public void DetachAll()
        {
            table.Clear();
        }

        public void Raise(CustomAttributesBase attribute, string key)
        {
            var bag = table.GetOrReturnNew(attribute.GetDroid());
            var handlers = bag.GetOrAddNew(key);
            foreach (var handler in handlers)
            {
                handler(attribute, new PropertyChangedEventArgs(key));
            }
        }
    }
}